package net.starwifi.duobao.web.db;

import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.mvc.BaseController;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.oauth.Principal;
import net.starwifi.duobao.service.GglUserService;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.WoService;
import net.starwifi.duobao.utils.IpUtils;
import net.starwifi.duobao.utils.StringUtils;
import net.starwifi.duobao.utils.WebUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2015/11/26.
 */
@Controller("apiWOController")
@RequestMapping("/wo")
public class WoController extends BaseController {

    @Autowired
    WoService woService;

    @Autowired
    MemberService memberService;

    @Autowired
    GglUserService gglUserService;

    /**获取号码后自动登陆  */
    @ResponseBody
    @RequestMapping(value = "/unikey",method = RequestMethod.GET)
    public Object unikey(HttpServletRequest request) {
        String unikey=StringUtils.getUUID().toLowerCase();
        return Message.success(unikey);
        //return Message.error("");
    }


    /**
     * 异步取号(unikey)
     */
    @ResponseBody
    @RequestMapping(value = "/nl",method = RequestMethod.GET)
    public Message getNum(HttpServletRequest request,HttpSession session,HttpServletResponse response,String unikey){
        if(unikey==null){
            return Message.error("unikey error");
        }
        Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
        if (principal != null) {
            return Message.success("success");
        }
        String woResult=woService.findNum(unikey);
        if(woResult==null){
            return Message.error("wo result error,type 0");
        }
        if(woResult.equals("0")){
            return Message.error("wo result error,type 1");
        }
        if(woResult.length()<11){
            return Message.error("wo result error,type 2");
        }
        String pMobile=woResult.split(",")[0];
        Member member=memberService.findByMobile(pMobile);
        if (member == null) {
            member=new Member();
            member.setUsername("m" + pMobile);
            String salt= net.starwifi.duobao.utils.StringUtils.getUUID();
            member.setSalt(salt);
            member.setMobile(pMobile);
            member.setIsEnabled(true);
            member.setIsLocked(false);
            member.setLoginFailureCount(0);
            member.setLockedDate(null);
            member.setBalance(BigDecimal.ZERO);
            member.setCurrencyBalance(BigDecimal.ZERO);
            member.setVirtualCurrency(BigDecimal.ZERO);
           try {
               if(request.getSession().getAttribute("cp")!=null){
                   member.setCpId((String)request.getSession().getAttribute("cp"));
               }
           }catch (Exception e){
               e.printStackTrace();
           }
        }
        if (!member.getIsEnabled()) {
            return Message.error("wo result error,type 1");
        }
        if(member.getVirtualCurrency()==null){
            member.setVirtualCurrency(BigDecimal.ZERO);
        }
        member.setLoginIp(IpUtils.getIpAddr(request));
        member.setLoginDate(new Date());
        member.setLoginFailureCount(0);
        if(member.getId()==null){
            memberService.save(member);
        }else{
            memberService.update(member);
        }
        //获取登录时间
        gglUserService.saveLog(member);
        Map<String, Object> attributes = new HashMap<String, Object>();
        Enumeration<?> keys = session.getAttributeNames();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            attributes.put(key, session.getAttribute(key));
        }
        session.invalidate();
        session = request.getSession();
        for (Map.Entry<String, Object> entry : attributes.entrySet()) {
            session.setAttribute(entry.getKey(), entry.getValue());
        }
        String userAgent=request.getHeader("User-Agent");
        String cookiePass= DigestUtils.md5Hex(userAgent + member.getPassword());
        session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), pMobile));
        session.setAttribute("pMobile",pMobile);
        WebUtils.addCookie(request, response, Member.COOKIE_USERNAME_NAME, member.getUsername());
        WebUtils.addCookie(request, response, Member.COOKIE_PASS_NAME, cookiePass);
        return Message.success("");
    }


    /**
     * 异步取号(unikey)
     */
    @ResponseBody
    @RequestMapping(value = "/api",method = RequestMethod.GET)
    public Message api(String unikey,String apiKey){
        if(unikey==null){
            return Message.error("unikey error");
        }
        if(!apiKey.equals("stx_app_api_001")){
            return Message.error("apiKey error");
        }
        String woResult=woService.findNum(unikey);
        if(woResult==null){
            return Message.error("wo result error,type 0");
        }
        if(woResult.equals("0")){
            return Message.error("wo result error,type 1");
        }
        if(woResult.length()<11){
            return Message.error("wo result error,type 2");
        }
        String pMobile=woResult.split(",")[0];
        return Message.success(pMobile);
    }

}
